<template>
  <div id="forum">
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        placeholder="搜索帖子"
        v-model:value="searchParams.title"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>

    <!-- 分类 -->
    <div style="display: flex; align-items: center;">
      <span style="margin-right: 8px;margin-bottom: 16px;">话题:&nbsp;&nbsp;</span>
      <a-tabs v-model:activeKey="selectedTopic" @change="doSearch" style="flex: 1;">
        <a-tab-pane key="all" tab="全部"></a-tab-pane>
        <a-tab-pane v-for="topic in topicList" :key="topic.id" :value="topic.id" :tab="topic.title"></a-tab-pane>
      </a-tabs>
      <!-- 新增发布帖子按钮 -->
      <a-button type="primary" @click="openPublishModal">发布帖子</a-button>
    </div>

    <!-- 帖子列表 -->
    <div class="post-list">
      <a-list item-layout="vertical" size="large" :data-source="dataList">
        <template #renderItem="{ item }">
          <a-list-item :key="item.id">
            <a-list-item-meta :description="item.content">
              <template #title>
                <router-link :to="'/post/' + item.id">{{ item.title }}</router-link>
              </template>
              <template #avatar>
                <a-avatar :src="item.userAvatar" />
              </template>
            </a-list-item-meta>
            <div slot="actions">
              <span>{{ formatTime(item.createTime) }}</span>
              <a-button type="link" @click="toggleFavorite(item)">
                {{ isFavorited(item) ? '已收藏' : '收藏' }}
              </a-button>
              <!-- 只有登录用户的帖子才显示删除和修改按钮 -->
              <template v-if="item.userId==currentUserId">
                <a-button type="link" @click="openEditModal(item)">修改</a-button>
                <a-button type="link" @click="confirmDelete(item.id)">删除</a-button>
              </template>
            </div>
            <div style="font-size: 12px; color: #888;">
              发布者: {{ item.userName }}  | 话题: {{ getTopicTitle(item.topicId) }}
            </div>
          </a-list-item>
        </template>
      </a-list>
    </div>

    <!-- 发布帖子模态框 -->
    <a-modal
      :visible="publishModalVisible"
      title="发布帖子"
      okText="发布"
      cancelText="取消"
      @ok="handlePublishPost"
      @cancel="closePublishModal"
    >
      <a-form :model="publishPostForm" layout="vertical" :rules="publishFormRules">
        <a-form-item label="帖子标题" name="title">
          <a-input v-model:value="publishPostForm.title" placeholder="输入帖子标题" />
        </a-form-item>
        <a-form-item label="话题" name="topicId">
          <a-select v-model:value="publishPostForm.topicId" placeholder="选择话题">
            <a-select-option v-for="topic in topicList" :key="topic.id" :value="topic.id">{{ topic.title }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="帖子内容" name="content">
          <a-textarea v-model:value="publishPostForm.content" placeholder="输入帖子内容" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改帖子模态框 -->
    <a-modal
      :visible="editModalVisible"
      title="修改帖子"
      okText="保存"
      cancelText="取消"
      @ok="handleEditPost"
      @cancel="closeEditModal"
    >
      <a-form :model="editPostForm" layout="vertical" :rules="publishFormRules">
        <a-form-item label="帖子标题" name="title">
          <a-input v-model:value="editPostForm.title" placeholder="输入帖子标题" />
        </a-form-item>
        <a-form-item label="话题" name="topicId">
          <a-select v-model:value="editPostForm.topicId" placeholder="选择话题">
            <a-select-option v-for="topic in topicList" :key="topic.id" :value="topic.id">{{ topic.title }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="帖子内容" name="content">
          <a-textarea v-model:value="editPostForm.content" placeholder="输入帖子内容" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { listTopicVoByPageUserUsingPost } from "@/api/topicController";
import { addPostUsingPost1, deletePostUsingPost1, listPostVoByPageUsingPost, updatePostUsingPost } from "@/api/postController";
import dayjs from 'dayjs';
import { addPostUsingPost, listFavoritePostVoByPageUsingPost } from '@/api/favoritePostController';
import {useLoginUserStore} from "@/stores/useLoginUserStore";



// 定义列
const topicList = ref<object[]>([]);
const selectedTopic = ref<string>('all');
const loading = ref<boolean>(true);
const userStore = useLoginUserStore();
// 模拟登录用户信息，实际应用中需要从登录状态获取
const currentUserId = useLoginUserStore().loginUser.id;

// 获取话题
const getCategoryTagOptions = async () => {
  const res = await listTopicVoByPageUserUsingPost({});
  if (res.data.code === 0 && res.data.data) {
    topicList.value = res.data.data.records ?? [];
  } else {
    message.error('加载选项失败' + res.data.message);
  }
};

onMounted(() => {
  getCategoryTagOptions();
});

// 数据
const dataList = ref([]);
const total = ref(0);

// 用户收藏的帖子ID集合
const favoritePosts = ref<string[]>([]);

// 搜索条件
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
});

// 分页参数
const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  onChange: (page: number, pageSize: number) => {
    searchParams.current = page;
    searchParams.pageSize = pageSize;
    fetchData();
  },
}));

// 获取数据
const fetchData = async () => {
  loading.value = true;
  const params = { ...searchParams };
  if (selectedTopic.value !== 'all') {
    params.topicId = selectedTopic.value;
  }
  const res = await listPostVoByPageUsingPost(params);
  if (res.data.data) {
    dataList.value = res.data.data.records ?? [];
    total.value = res.data.data.total ?? 0;
  } else {
    message.error('获取帖子数据失败，' + res.data.message);
  }
  loading.value = false;
};

// 删除数据
const doDelete = async (id: string) => {
  if (!id) return;
  const res = await deletePostUsingPost1({ id });
  if (res.data.code === 0) {
    message.success('删除成功');
    await fetchData();
  } else {
    message.error('删除失败');
  }
};

// 页面加载时请求一次
onMounted(() => {
  fetchData();
  fetchFavoritePosts();
});

// 获取数据
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1;
  fetchData();
};

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current;
  searchParams.pageSize = page.pageSize;
  fetchData();
};
const router = useRouter();

// 判断是否已收藏
const isFavorited = (post: any) => favoritePosts.value.includes(post.id);

// 收藏/取消收藏
const toggleFavorite = async (post: any) => {
  if (isFavorited(post)) {
    message.warn('该帖子已收藏');
    return;
  }
  // 添加收藏
  const res = await addPostUsingPost({ postId: post.id });
  if (res.data.code === 0) {
    favoritePosts.value.push(post.id);
    message.success('已收藏');
  } else {
    message.error('添加收藏失败');
  }
};

// 获取收藏帖子
async function fetchFavoritePosts() {
  const res = await listFavoritePostVoByPageUsingPost({ ...searchParams });
  if (res.data.data) {
    // 提取帖子ID列表
    favoritePosts.value = res.data.data.records.map((post: any) => post.postId);
    console.log('收藏的帖子:', favoritePosts.value);
    total.value = res.data.data.total ?? 0;
    // message.success('获取收藏帖子成功');
  } else {
    message.error('获取收藏帖子数据失败' + res.data.message);
  }
}

// 发布帖子模态框相关
const publishModalVisible = ref(false);
const publishPostForm = reactive({
  title: '',
  topicId: '',
  content: ''
});

// 修改帖子模态框相关
const editModalVisible = ref(false);
const editPostForm = reactive({
  id: '',
  title: '',
  topicId: '',
  content: ''
});

// 发布表单验证规则
const publishFormRules = reactive({
  title: [
    {
      required: true,
      message: '帖子标题为必填项',
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      message: '帖子内容为必填项',
      trigger: 'blur'
    }
  ]
});

// 打开发布帖子模态框
const openPublishModal = () => {
  publishModalVisible.value = true;
  publishPostForm.title = '';
  publishPostForm.topicId = '1';
  publishPostForm.content = '';
};

// 关闭发布帖子模态框
const closePublishModal = () => {
  publishModalVisible.value = false;
};

// 处理发布帖子
const handlePublishPost = async () => {
  if (publishPostForm.title && publishPostForm.content) {
    const res = await addPostUsingPost1({ ...publishPostForm });
    if (res.data.code === 0) {
      message.success('发布帖子成功');
      closePublishModal();
      await fetchData();
    } else {
      message.error('发布帖子失败');
    }
  }
};

// 打开修改帖子模态框
const openEditModal = (post: any) => {
  editModalVisible.value = true;
  editPostForm.id = post.id;
  editPostForm.title = post.title;
  editPostForm.topicId = post.topicId;
  editPostForm.content = post.content;
};

// 关闭修改帖子模态框
const closeEditModal = () => {
  editModalVisible.value = false;
};

// 处理修改帖子
const handleEditPost = async () => {
  if (editPostForm.title && editPostForm.content) {
    const res = await updatePostUsingPost({ ...editPostForm });
    if (res.data.code === 0) {
      message.success('修改帖子成功');
      closeEditModal();
      await fetchData();
    } else {
      message.error('修改帖子失败');
    }
  }
};

// 确认删除帖子
const confirmDelete = (id: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除该帖子吗？',
    onOk: () => doDelete(id),
  });
};

// 判断帖子是否属于当前登录用户
const isCurrentUserPost = (post: any) =>{  post.userId === currentUserId;
  console.log(post.userId)
  console.log(currentUserId)
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
};

// 获取话题标题
const getTopicTitle = (topicId: string) => {
  const topic = topicList.value.find((t: any) => t.id === topicId);
  return topic ? topic.title : '未知话题';
};
</script>

<style scoped>
#forum {
  width: 100%;
  margin: 0 auto;
}

#forum .search-bar {
  width: 60%;
  margin: 20px auto;
}

.post-list {
  padding: 20px;
}
</style>
